import React from 'react';
import {
    StyleSheet,
    View,
    Text,
    Button,
} from 'react-native';
var TimerMixin = require('react-timer-mixin');

export default class TimersView extends React.Component{

    constructor(props) {
         super(props);  
         this.state={
           content:'',
           sum : 0,
         };
    }
    componentDidMount() {
      this.timer = setTimeout(() => { 
      	this.setState({content:'我是定时器setTimeout只会执行一次'});
      },500);
    }
    componentWillUnmount() {
      // 如果存在this.timer，则使用clearTimeout清空。
      // 如果你使用多个timer，那么用多个变量，或者用个数组来保存引用，然后逐个clear
      this.timer && clearTimeout(this.timer);
      this.interval && clearInterval(this.interval);
    }

    render(){
    	return(
    		<View style={{margin:20}}>
    		        <Text style = {styles.txt}>{this.state.content}</Text>
    		        <Text></Text>
    		        <Text style = {styles.txt}>我是定时器setInterVal间隔执行，打印：+ {this.state.sum}</Text>
    		        <Text></Text>
    		        <Button
    		            title = '点击我开始间隔计时'
    		            style = { styles.btn} 
    		            onPress = { ()=> {this.interval = setInterval(()=> {this.setState({sum : this.state.sum + 1 });},500);}}
    		        />
    		         <Text style = {{height : 20 }}/>
    		        <Button  
    		             title = '点击我取消计时'
    		             style = { styles.btn} 
    		             onPress = {()=> {this.interval && clearInterval(this.interval);}}></Button>
    		</View>

    	);
    }

}

const styles = StyleSheet.create({
  txt: {
    fontSize: 30,
    textAlign: 'center',
    margin: 50,
  },
  btn: {
     height : 50,
  },

});


